import { FC, useState, useEffect } from 'react';
import { CloseCircleOutlined } from '@ant-design/icons';
import _ from 'lodash';
import { xhr_post_json, xhr_get} from '../_common/request';
import './select-other-values.less';
interface IMultInput{
    multValue: Array<any> | string,
    api?: {
        url?: string | null,
        params?: any,
        type: "GET"|"POST",
    }
    onChange: (a: any)=>{}
}
const MultipleInput: FC<IMultInput>=(props:IMultInput) => {
    const [ multValues, setMultValue ] = useState<any>()
    const { multValue=[], api, onChange } = props;
    useEffect(()=>{
        setMultValue(multValue);
    }, [multValue])
    useEffect(()=>{
      if(api) return ;
      const func = async() =>{
      try {
        const res:any =  await ((api && (api as any).type) as any)?.toLocaleUpperCase() === 'GET' ? xhr_get((api as any).url, (api as any).params):
        xhr_post_json((api as any).url, (api as any).params);
        if(res.result){
            setMultValue(res?.result)   
        }
      } catch (error) {
          console.error(`获取默认值失败`)
      }
      }
      func();
    },[JSON.stringify(api)])
    // 删除当前值
    const onDelete=(item:any)=>{
       const items = multValues.concat([]);
       const it = _.remove(items, (i:any)=>(i===item));
       if(onChange){
        onChange(it);
       }
       setMultValue(it);
    }
    return <div>
         {
             multValues.length? multValues?.map((item:any, index:number)=>{
                 return  <div onClick={onDelete} className='valueItem'>
                 {item}
                 <CloseCircleOutlined />
             </div>
             }): null
         }
    </div>
}

export default MultipleInput